<template>
  <el-dialog
    title="班组详情"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    :width="device == 'desktop' ? '70%' : '90%'"
    v-dialog-drag
    :close-on-click-modal="false"
    :destroy-on-close="true"
    top="5vh"
    @close="handleClose()"
    @open="handleOpen()"
  >
    <div class="dialog-body-content" :key="updateKey" v-loading="loading">
      <el-collapse
        :value="[
          '1',
          '2',
          'members',
          'task',
          'rawMaterial',
          'equipOperationStatus',
          'taskProcessingStatus',
          'abnormalHandlingStatus',
          'stationLog',
        ]"
      >
        <el-collapse-item name="1">
          <template slot="title">
            <PartitionTitle title="班组详情"></PartitionTitle>
          </template>
          <el-form
            ref="BaseForm"
            :model="baseForm"
            label-width="140px"
            size="small"
            disabled
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="所属车间" prop="workshopName">
                  <el-input
                    type="text"
                    v-model="baseForm.workshopName"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="产线" prop="lineName">
                  <el-input type="text" v-model="baseForm.lineName"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="班组" prop="groupName">
                  <el-input type="text" v-model="baseForm.groupName"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="实际工作开始时间" prop="workStartTime">
                  <el-input
                    type="text"
                    v-model="baseForm.workStartTime"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="是否头班">
                  <el-input
                    type="text"
                    :value="baseForm.preTakeAndHandVo ? '否' : '是'"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <!-- 生产任务单，车间类型为水处理车间、调配车间、生产公共的，接班时不需要产生工单信息 -->
          <Task
            v-if="
              takeoverDetailsData &&
              !['WATER', 'ALLOCATE', 'PRODUCTION_PUBLIC'].includes(
                takeoverDetailsData.workshopType
              )
            "
            status="4"
            detailKey="takeoverDetail"
          ></Task>
          <Members
            :status="memberEditable ? '1' : '4'"
            detailKey="takeoverDetail"
          ></Members>
        </el-collapse-item>
      </el-collapse>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button
        type="default"
        :loading="saveloading"
        @click="dialogVisible = false"
        >取消</el-button
      >
      <el-button
        v-if="memberEditable"
        type="primary"
        :loading="saveloading"
        @click="handleSaveStationMember"
        >保存</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import Task from "../components/task";
import Members from "../components/members";
import { mapMutations, mapState, mapGetters } from "vuex";
import {
  getTakeoverInfoById,
  saveStationUserInfos,
} from "@/api/shifts/turnOnDuty";
export default {
  components: {
    Task,
    Members,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 被接替的班组，有值，表示连续生产，为null，表示非连续生产
    group: {
      type: Object,
      default: null,
    },
    memberEditable: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      updateKey: 1,
      loading: false,
      saveloading: false,
      // 接班详情
      baseForm: {
        factoryDeptId: null,
        factoryDeptCode: null,
        workshopId: null,
        workshopName: null,
        lineName: null,
        lineId: null,
        groupName: null,
        groupId: null,
        workStartTime: null,
        preTakeAndHandVo: null,
      },
      workshopOptions: [], //车间列表
      lineOptions: [], //产线列表
      groupOptions: [], // 班组列表
    };
  },
  computed: {
    ...mapGetters(["device"]),
    ...mapState({
      takeoverDetailsData: (state) => state.turnOnDuty.takeoverDetail,
    }),
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val);
      },
      get() {
        return this.visible;
      },
    },
  },
  methods: {
    ...mapMutations("turnOnDuty", ["SET_TAKEOVERDETAIL"]),
    handleClose() {
      this.SET_TAKEOVERDETAIL(null);
      this.baseForm = {
        factoryDeptId: null,
        factoryDeptCode: null,
        workshopId: null,
        workshopName: null,
        lineName: null,
        lineId: null,
        groupName: null,
        groupId: null,
        workStartTime: null,
        preTakeAndHandVo: null,
      };
      this.$refs.BaseForm.resetFields();
    },
    handleOpen() {
      this.getTakeOverDetails();
    },
    // 查询接班详情
    getTakeOverDetails() {
      this.loading = true;

      getTakeoverInfoById(this.group.id)
        .then((res) => {
          this.SET_TAKEOVERDETAIL(res?.data || null);

          this.baseForm.factoryDeptId = res?.data?.factoryDeptId || null;
          this.baseForm.factoryDeptCode = res?.data?.factoryDeptCode || null;
          this.baseForm.workshopId = res?.data?.workshopId || null;
          this.baseForm.workshopName = res?.data?.workshopName || null;
          this.baseForm.lineId = res?.data?.lineId || null;
          this.baseForm.lineName = res?.data?.lineName || null;
          this.baseForm.groupId = res?.data?.groupId || null;
          this.baseForm.groupName = res?.data?.groupName || null;
          this.baseForm.workStartTime = res?.data?.workStartTime || null;
          this.baseForm.preTakeAndHandVo = res?.data?.preTakeAndHandVo || null;

          this.updateKey++;
          this.loading = false;
        })
        .catch(() => {
          this.SET_TAKEOVERDETAIL(null);

          this.baseForm.factoryDeptId = null;
          this.baseForm.factoryDeptCode = null;
          this.baseForm.workshopId = null;
          this.baseForm.workshopName = null;
          this.baseForm.lineId = null;
          this.baseForm.lineName = null;
          this.baseForm.groupId = null;
          this.baseForm.groupName = null;
          this.baseForm.workStartTime = null;
          this.baseForm.preTakeAndHandVo = null;

          this.updateKey++;
          this.loading = false;
        });
    },
    handleSaveStationMember() {
      if (!this.takeoverDetailsData) {
        return null;
      }
      const param = {
        produceLogId: this.takeoverDetailsData.produceLogId,
        lineId: this.takeoverDetailsData.lineId,
        groupId: this.takeoverDetailsData.groupId,
        produceDate: this.takeoverDetailsData.produceDate,
        workStationUserVos:
          this.takeoverDetailsData.workStationUserVos?.map((ele) => ({
            workStationId: ele.workStationId,
            workType: ele.workType,
            workStationUserHourVos: ele.workStationUserHourVos.map((user) => ({
              username: user.username,
            })),
          })) || [],
      };

      // 校验
      // 每个工位必须配人
      const emtyUser = param.workStationUserVos.find(
        (ele) => !ele.workStationUserHourVos?.length
      );
      if (emtyUser) {
        this.msgWarning("每个工位必须分配人员");
        return false;
      }

      this.$confirm("是否确定开始工作？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.saveloading = true;
          saveStationUserInfos(param)
            .then((res) => {
              this.msgSuccess("操作成功！");
              this.dialogVisible = false;

              // 刷新基础权限数据
              this.$store.dispatch("getAllData");
              this.$store.dispatch("getWorkUserInfo");
            })
            .finally(() => {
              this.saveloading = false;
            });
        })
        .catch(() => {});
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-collapse {
  border: none;
  .el-collapse-item__wrap {
    border: none;
  }
}
.block-title {
  margin-bottom: 0;
}
.box {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}
.el-form {
  .el-select,
  .el-date-editor.el-input {
    width: 100%;
  }
}
</style>
